﻿using Magicodes.WeiChat.Helpers;
using Magicodes.WeiChat.Data.Models;
using Magicodes.WeiChat.Data.Models.Site;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using Magicodes.Logger;

namespace Magicodes.WeiChat.Controllers.WebApi
{
    [RoutePrefix("api/Site_Notifies")]
    public class Site_NotifiesApiController : WebApiControllerBase
    {
        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult Remove(int id)
        {
            var uid = UserId;
            if (!db.Site_ReadNotifies.Any(p => p.NotifyId == id && p.CreateBy == uid))
            {
                var read = new Site_ReadNotify()
                {
                    CreateBy = uid,
                    CreateTime = DateTime.Now,
                    NotifyId = id
                };
                db.Site_ReadNotifies.Add(read);
                db.SaveChanges();
            }
            return Ok();
        }

        [HttpGet]
        [Route("Unread/Count")]
        public IHttpActionResult GetUnreadCount()
        {
            var userId = UserId;
            var userKey = "User_" + userId;
            var user = db.Users.Find(userId);
            if (user == null)
            {
                Logger.Log(LoggerLevels.Error, "User 不存在！");
                return Ok(new { TotalCount = 0 });
            }
            //根据登录角色获取
            var tenantId = user.TenantId;
            var agentTennantId = user.AgentTennantId;
            //如果当前租户为系统租户，则允许代理其他租户操作
            if (db.Account_Tenants.Any(p => (p.Id == tenantId) && p.IsSystemTenant))
            {
                //系统租户使用AgentTennantId
                if ((user.AgentTennantId != default(int)) && (user.AgentTennantId != tenantId))
                    tenantId = user.AgentTennantId;
            }
            var tenantKey = "Tenant_" + tenantId;

            //连接时通知
            var queryable = db.Site_Notifies.Where(p => (p.Receiver == userKey || p.Receiver == tenantKey) && !db.Site_ReadNotifies.Any(p1 => p1.NotifyId == p.Id && p1.CreateBy == user.Id));
            if (queryable.Any())
            {
                var count = queryable.Count();
                return Ok(new { TotalCount = count });
            }
            else
            {
                return Ok(new { TotalCount = 0 });
            }
        }
    }
}